const { ErrorModel } = require("../model/resModel");
const jwt = require("jsonwebtoken");
const { loginCheck } = require("../controller/user");

module.exports = (req, res, next) => {
  const authorizationHeader = req.headers["authorization"];
  let token;
  if (authorizationHeader) {
    token = authorizationHeader.split(" ")[1];
  }
  if (token) {
    jwt.verify(token, "#mongo_dect", (err, decoded) => {
      if (err) {
        res.json(new ErrorModel("未登录"));
      } else {
        loginCheck(decoded.id).then((userData) => {
          if (userData.user_email) {
            // console.log(userData.user_email);
            next();
            return;
          } else {
            res.json(new ErrorModel("未登录"));
          }
        });
      }
    });
  } else {
    res.json(new ErrorModel("未登录"));
  }
};
